package service;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import config.Config;
import config.SocketConfig;

//客户端
public class SignBroadSender implements Runnable{
	private DatagramSocket client;
	private DatagramPacket sendPack;
	private String str;
	
	public  SignBroadSender(String sendMsg, int broadcastPort) {
		this.str = sendMsg;
		try {
			/*
			 * 在Java UDP中单播与广播的代码是相同的,要实现具有广播功能的程序只需要使用广播地址即可, 例如：这里使用了本地的广播地址
			 */
			InetAddress inetAddr = InetAddress.getByName("255.255.255.255");
//			InetAddress ip = InetAddress.getLocalHost();
//			String ipAddress = ip.getHostAddress();
//			String sendMsg = Config.className+":"+SocketConfig.ipAddress+":"+SocketConfig.socketPort;
			
			System.out.println("sendMsg: "+sendMsg);
			byte[] msg = sendMsg.getBytes();
			
			client = new DatagramSocket();
			sendPack = new DatagramPacket(msg, msg.length,
					inetAddr, broadcastPort);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		try {
			while(Config.isSign) {
				client.send(sendPack);
				System.out.println(str+"  Client send msg complete");
				Thread.sleep(500);
			}
			client.close();
			client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
